export const useTagsViewStore = defineStore("tagsView", () => {
     const visitedViews = ref<TagView[]>([]);
       const cachedViews = ref<string[]>([]);
     // 添加已访问视图到已访问视图列表中
     const addVisitedView = (view: TagView) => {
        // 如果已经存在 则不添加
       if(visitedViews.value.some(v => v.path === view.path)){
        return
       }
    //    如果视图是固定 在开头添加
       if(view.affix){
        visitedViews.value.unshift(view)
       }else{
        // 如果视图不是固定 在末尾添加
           visitedViews.value.push(view)
       }
     }
     const addCachedView = (view:TagView)=>{
        const viewName = view.name
        if(cachedViews.value.includes(viewName)){
            return
        }
        if(view.keepAlive){
            cachedViews.value.push(viewName)
        }
     }
     const addView=(view: TagView)=> {
    addVisitedView(view);
    addCachedView(view);
  }
  // 删除已访问视图
  const delVisitedView = (view:TagView)=>{
    return new Promise((resolve)=>{
        for(const [i,v] of visitedViews.value.entries()){
            if(v.path === view.path){
                visitedViews.value.splice(i,1)
                break
            }
            }
             resolve([...visitedViews.value]);
    })
  }
  const delCachedView = (view:TagView)=>{
    console.log(view);
    
    const viewName = view.name
    return new Promise((resolve)=>{
        const index = cachedViews.value.indexOf(viewName)
        // 如果索引大于-1 则删除
        index > -1 && cachedViews.value.splice(index,1)
        resolve([...cachedViews.value])
    })
  }
  const delView = (view:TagView)=>{
    return new Promise((resolve)=>{
        delVisitedView(view)
        delCachedView(view)
        resolve({
            visitedViews:[...visitedViews.value],
            cachedViews:[...cachedViews.value]
        })
    })
  }

    return {visitedViews,cachedViews,addVisitedView,addCachedView,addView,delVisitedView,delCachedView,delView}
});
